<template>
  <div class="vehicle-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
        <el-form-item label="车辆名称" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入车辆名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" clearable></el-input>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="brandId">
          <el-select v-model="searchForm.brandId" placeholder="请选择车辆品牌" clearable>
            <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="type">
          <el-select v-model="searchForm.type" placeholder="请选择车辆类型" clearable>
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择车辆状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增车辆</el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="success" icon="el-icon-upload2" @click="handleImport">导入</el-button>
        <el-button type="warning" icon="el-icon-download" @click="handleExport">导出</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="车辆名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="licensePlate" label="车牌号" width="120" align="center"></el-table-column>
        <el-table-column prop="brandName" label="品牌" width="120"></el-table-column>
        <el-table-column prop="seriesName" label="车系" width="120"></el-table-column>
        <el-table-column label="车辆类型" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getTypeTag(scope.row.type)">{{ getTypeName(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="seats" label="座位数" width="80" align="center"></el-table-column>
        <el-table-column prop="dailyRent" label="日租金" width="100" align="center">
          <template slot-scope="scope">
            <span>¥ {{ scope.row.dailyRent }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车辆状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusName(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="storeName" label="所属门店" width="120"></el-table-column>
        <el-table-column label="车辆图片" width="100" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.image"
              style="width: 60px; height: 40px"
              :src="scope.row.image" 
              :preview-src-list="[scope.row.image]">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown size="mini" split-button type="info" @command="(command) => handleCommand(command, scope.row)">
              更多
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                <el-dropdown-item command="changeStatus" :disabled="scope.row.status === 2">修改状态</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" @close="resetForm('form')">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入车辆名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-model="form.licensePlate" placeholder="请输入车牌号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆品牌" prop="brandId">
              <el-select v-model="form.brandId" placeholder="请选择车辆品牌" @change="handleBrandChange">
                <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆系列" prop="seriesId">
              <el-select v-model="form.seriesId" placeholder="请选择车辆系列">
                <el-option v-for="item in seriesOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择车辆类型">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="座位数" prop="seats">
              <el-input-number v-model="form.seats" :min="2" :max="20" placeholder="请输入座位数"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="变速箱类型" prop="transmissionType">
              <el-select v-model="form.transmissionType" placeholder="请选择变速箱类型">
                <el-option label="手动" :value="1"></el-option>
                <el-option label="自动" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排量" prop="displacement">
              <el-input v-model="form.displacement" placeholder="请输入排量"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="燃油类型" prop="fuelType">
              <el-select v-model="form.fuelType" placeholder="请选择燃油类型">
                <el-option label="汽油" :value="1"></el-option>
                <el-option label="柴油" :value="2"></el-option>
                <el-option label="电动" :value="3"></el-option>
                <el-option label="混合动力" :value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日租金" prop="dailyRent">
              <el-input-number v-model="form.dailyRent" :precision="2" :step="10" :min="0" placeholder="请输入日租金"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择车辆状态">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆颜色" prop="color">
              <el-input v-model="form.color" placeholder="请输入车辆颜色"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出厂年份" prop="productionYear">
              <el-date-picker
                v-model="form.productionYear"
                type="year"
                placeholder="选择年份"
                value-format="yyyy"
                format="yyyy"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="里程数" prop="mileage">
              <el-input-number v-model="form.mileage" :min="0" placeholder="请输入里程数"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属门店" prop="storeId">
              <el-select v-model="form.storeId" placeholder="请选择所属门店">
                <el-option v-for="item in storeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否新车" prop="isNew">
              <el-switch
                v-model="form.isNew"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="车辆图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="车辆描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入车辆描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改状态对话框 -->
    <el-dialog title="修改车辆状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(currentStatus)">{{ getStatusName(currentStatus) }}</el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择车辆状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmChangeStatus">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { mapGetters } from 'vuex'

export default {
  name: 'VehicleList',
  computed: {
    ...mapGetters([
      'token'
    ]),
    uploadHeaders() {
      return {
        Authorization: 'Bearer ' + this.token
      }
    }
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        licensePlate: '',
        brandId: '',
        type: '',
        status: ''
      },
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      selectedIds: [],
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增车辆',
      // 表单数据
      form: {
        id: null,
        name: '',
        licensePlate: '',
        brandId: '',
        seriesId: '',
        type: '',
        seats: 5,
        transmissionType: 2, // 默认自动
        displacement: '',
        fuelType: 1, // 默认汽油
        dailyRent: 0,
        status: 1, // 默认可用
        color: '',
        productionYear: new Date().getFullYear().toString(),
        mileage: 0,
        image: '',
        description: '',
        storeId: '',
        isNew: 1 // 默认新车
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入车辆名称', trigger: 'blur' }],
        licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择车辆品牌', trigger: 'change' }],
        seriesId: [{ required: true, message: '请选择车辆系列', trigger: 'change' }],
        type: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
        seats: [{ required: true, message: '请输入座位数', trigger: 'blur' }],
        dailyRent: [{ required: true, message: '请输入日租金', trigger: 'blur' }],
        storeId: [{ required: true, message: '请选择所属门店', trigger: 'change' }]
      },
      // 选项数据
      brandOptions: [],
      seriesOptions: [],
      storeOptions: [],
      typeOptions: [
        { value: 1, label: '经济型' },
        { value: 2, label: '舒适型' },
        { value: 3, label: '豪华型' },
        { value: 4, label: 'SUV' },
        { value: 5, label: 'MPV' }
      ],
      statusOptions: [
        { value: 1, label: '可用' },
        { value: 2, label: '已租' },
        { value: 3, label: '维修中' },
        { value: 4, label: '报废' }
      ],
      // 状态修改
      statusDialogVisible: false,
      statusForm: {
        id: null,
        status: ''
      },
      currentStatus: null
    }
  },
  created() {
    this.fetchData()
    this.fetchBrands()
    this.fetchStores()
  },
  methods: {
    // 获取车辆列表数据
    fetchData() {
      this.loading = true
      const params = {
        current: this.pageParams.current,
        size: this.pageParams.size,
        ...this.searchForm
      }
      
      request({
        url: '/car-vehicle/vehicles/page',
        method: 'get',
        params
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取品牌列表
    fetchBrands() {
      request({
        url: '/car-vehicle/vehicle-brands/list/available',
        method: 'get'
      }).then(res => {
        this.brandOptions = res.data
      })
    },
    // 根据品牌ID获取车系列表
    fetchSeries(brandId) {
      request({
        url: `/car-vehicle/vehicle-series/list/available/brand/${brandId}`,
        method: 'get'
      }).then(res => {
        this.seriesOptions = res.data
      })
    },
    // 获取门店列表
    fetchStores() {
      request({
        url: '/car-vehicle/stores/list',
        method: 'get'
      }).then(res => {
        this.storeOptions = res.data
      })
    },
    // 处理品牌变更
    handleBrandChange(brandId) {
      this.form.seriesId = ''
      this.fetchSeries(brandId)
    },
    // 处理搜索
    handleSearch() {
      this.pageParams.current = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 处理选择变更
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchData()
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size
      this.pageParams.current = 1
      this.fetchData()
    },
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增车辆'
      this.form = {
        id: null,
        name: '',
        licensePlate: '',
        brandId: '',
        seriesId: '',
        type: '',
        seats: 5,
        transmissionType: 2,
        displacement: '',
        fuelType: 1,
        dailyRent: 0,
        status: 1,
        color: '',
        productionYear: new Date().getFullYear().toString(),
        mileage: 0,
        image: '',
        description: '',
        storeId: '',
        isNew: 1
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑车辆'
      this.form = { ...row }
      // 如果有品牌ID，获取对应的车系列表
      if (row.brandId) {
        this.fetchSeries(row.brandId)
      }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该车辆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/car-vehicle/vehicles/${row.id}`,
          method: 'delete'
        }).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    // 处理批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的车辆')
        return
      }
      this.$confirm(`确认删除选中的${this.selectedIds.length}辆车?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/car-vehicle/vehicles/batch',
          method: 'delete',
          data: this.selectedIds
        }).then(() => {
          this.$message.success('批量删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    // 处理导入
    handleImport() {
      this.$message.info('导入功能开发中')
    },
    // 处理导出
    handleExport() {
      this.$message.info('导出功能开发中')
    },
    // 处理更多操作
    handleCommand(command, row) {
      if (command === 'detail') {
        this.$router.push(`/vehicle/detail/${row.id}`)
      } else if (command === 'changeStatus') {
        this.statusForm.id = row.id
        this.statusForm.status = row.status
        this.currentStatus = row.status
        this.statusDialogVisible = true
      }
    },
    // 确认修改状态
    confirmChangeStatus() {
      request({
        url: `/car-vehicle/vehicles/${this.statusForm.id}/status/${this.statusForm.status}`,
        method: 'put'
      }).then(() => {
        this.$message.success('状态修改成功')
        this.statusDialogVisible = false
        this.fetchData()
      })
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/car-vehicle/vehicles/save',
            method: 'post',
            data: this.form
          }).then(() => {
            this.$message.success(`${this.form.id ? '更新' : '添加'}成功`)
            this.dialogVisible = false
            this.fetchData()
          })
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.form.image = res.data.url;
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败：' + res.message);
      }
    },
    // 图片上传前处理
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 获取车辆类型名称
    getTypeName(type) {
      const found = this.typeOptions.find(item => item.value === type)
      return found ? found.label : '未知'
    },
    // 获取车辆类型标签样式
    getTypeTag(type) {
      const map = {
        1: 'info',
        2: 'success',
        3: 'warning',
        4: 'primary',
        5: 'danger'
      }
      return map[type] || 'info'
    },
    // 获取车辆状态名称
    getStatusName(status) {
      const found = this.statusOptions.find(item => item.value === status)
      return found ? found.label : '未知'
    },
    // 获取车辆状态标签样式
    getStatusTag(status) {
      const map = {
        1: 'success',
        2: 'info',
        3: 'warning',
        4: 'danger'
      }
      return map[status] || 'info'
    },
    // 自定义上传方法
    customUpload(event) {
      const file = event.file
      const formData = new FormData()
      formData.append('file', file)

      request({
        url: '/car-integration/files/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.code === 200) {
          this.handleImageSuccess(res, file)
        } else {
          this.$message.error('上传失败：' + res.message)
        }
      }).catch(() => {
        this.$message.error('上传失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.vehicle-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
      
      .el-button {
        margin-right: 10px;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 100px;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }
}
</style> 